package springboot.rabbitmq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于插件的延迟队列的配置类
 */
@Configuration
public class DelayedQueueConfig {
    
    // 延迟交换机名称
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    // 延迟队列名称
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    // 路由key
    public static final String DELAYED_ROUTING_KEY_NAME = "delayed.routing.key";

    /**
     * 自定义延迟交换机
     * @return 自定义延迟交换机
     */
    @Bean(value = "delayedExchange")
    public CustomExchange delayedExchange(){
        Map<String,Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        return new CustomExchange(DELAYED_EXCHANGE_NAME, "x-delayed-message", true, false, args);
    }

    /**
     * 延迟队列
     * @return 延迟队列
     */
    @Bean(value = "delayedQueue")
    public Queue delayedQueue(){
        return new Queue(DELAYED_QUEUE_NAME);
    }

    /**
     * 延迟队列和延迟交换机绑定
     * @param delayedQueue 队列
     * @param delayedExchange 交换机
     * @return 绑定
     */
    @Bean
    public Binding bindingDelayedQueue(@Qualifier("delayedQueue") Queue delayedQueue,
                                       @Qualifier("delayedExchange") CustomExchange delayedExchange){
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY_NAME).noargs();
    }
}
